<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form ref="queryFormRef" :model="innerTopicQueryForm" :inline="true">
        <el-form-item :label="$t('innerTopic.topicPubName')" prop="topicPubName">
          <el-input
              v-model="innerTopicQueryForm.topicPubName"
              :placeholder="
              $t('common.placeholderInput') + $t('innerTopic.topicPubName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('innerTopic.topicSubName')" prop="topicSubName">
          <el-input
              v-model="innerTopicQueryForm.topicSubName"
              :placeholder="
              $t('common.placeholderInput') + $t('innerTopic.topicSubName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>

        <el-form-item>
          <el-button @click="search" type="primary" icon="Search">{{
              $t("common.search")
            }}
          </el-button>
          <el-button @click="addinnerTopic" type="primary" icon="Plus">{{
              $t("common.add")
            }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 2. 引入通用表单对话框组件 -->
    <CommonFormDialog
        :dialog-title="dialogTitle"
        v-model="dialogVisible"
        :dialog-width="dialogWidth"
        :form-data="innerTopicForm"
        :form-rules="innerTopicRules"
        :submit-loading="submitLoading"
        @close="close"
        @cancel="cancel"
        @submit="handleFormSubmit"
        @before-close="handleDialogBeforeClose"
        ref="dialogRef"
    >
      <!-- 2.1 自定义表单项（插槽：标签的“名称”和“排序”） -->
      <template #formItems>
        <el-form-item :label="$t('innerTopic.topicAssociationMode')" prop="topicAssociationMode">
          <el-select
              v-model="innerTopicForm.topicAssociationMode"
              :placeholder="
              $t('common.placeholderSelect') + $t('innerTopic.topicAssociationMode')
            "
          >
            <el-option
                v-for="(item, index) in topicAssociationModeEnums"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('innerTopic.topicPubSingalTypeParam')" prop="topicPubSingalTypeParam">
          <el-select
              @change="handleTopicPubSingalTypeParamChange"
              v-model="innerTopicForm.topicPubSingalTypeParam"
              :placeholder="
              $t('common.placeholderSelect') + $t('innerTopic.topicPubSingalTypeParam')
            "
          >
            <el-option
                v-for="(item, index) in singalTypeParamEnums"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.endesc"
            />
          </el-select>
        </el-form-item>
        <template v-if="innerTopicForm.topicAssociationMode != 1">
        <el-form-item :label="$t('innerTopic.topicPubName')" prop="topicPubName"
        >
          <el-input
              v-model="innerTopicForm.topicPubName"
              @change="handleTopicPubNameChange"
              :placeholder="
              $t('common.placeholderInput') + $t('innerTopic.topicPubName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        </template>
        <template v-if="innerTopicForm.topicAssociationMode != 0">
          <el-form-item :label="$t('innerTopic.topicSubName')" prop="topicSubName"
          >
            <el-input
                v-model="innerTopicForm.topicSubName"
                :placeholder="
              $t('common.placeholderInput') + $t('innerTopic.topicSubName')
            "
                clearable
                maxLength="50"
            />
          </el-form-item>
        </template>

        <el-form-item :label="$t('innerTopic.topicPubDeviceParam')" prop="topicPubDeviceParam">
          <el-input
              v-model="innerTopicForm.topicPubDeviceParam"
              :placeholder="
              $t('common.placeholderInput') + $t('innerTopic.topicPubDeviceParam')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>

        <el-form-item :label="$t('innerTopic.topicPubSysunitTypeParam')" prop="topicPubSysunitTypeParam">
          <el-select
              v-model="innerTopicForm.topicPubSysunitTypeParam"
              :placeholder="
              $t('common.placeholderSelect') + $t('innerTopic.topicPubSysunitTypeParam')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in emsSyCategorEnums"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.endesc"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('innerTopic.orderNo')" prop="topicSequence">
          <el-input-number
              :min="0" :max="9999999"
              v-model="innerTopicForm.topicSequence"
              :placeholder="
              $t('common.placeholderInput') + $t('innerTopic.orderNo')
            "
          />
        </el-form-item>
        <el-form-item :label="$t('innerTopic.topicPubAddrStartParam')" prop="topicPubAddrStartParam">
          <el-input-number
              :min="0" :max="9999999"
              v-model="innerTopicForm.topicPubAddrStartParam"
              :placeholder="
              $t('common.placeholderInput') + $t('innerTopic.topicPubAddrStartParam')
            "
          />
        </el-form-item>
        <el-form-item :label="$t('innerTopic.topicPubAddrNumParam')" prop="topicPubAddrNumParam">
          <el-input-number
              :min="1" :max="9999999"
              v-model="innerTopicForm.topicPubAddrNumParam"
              :placeholder="
              $t('common.placeholderInput') + $t('innerTopic.topicPubAddrNumParam')
            "
          />
        </el-form-item>
        <template v-if="innerTopicForm.topicPubSingalTypeParam=='yt' ">
          <el-form-item :label="$t('innerTopic.topicPubControlValueYtParam')" prop="topicPubControlValueYtParam">
            <el-input-number
                :min="1" :max="9999999"
                v-model="innerTopicForm.topicPubControlValueYtParam"
                :placeholder="
              $t('common.placeholderInput') + $t('innerTopic.topicPubControlValueYtParam')
            "
            />
          </el-form-item>
        </template>
        <template v-if="innerTopicForm.topicPubSingalTypeParam=='yk' ">
          <el-form-item :label="$t('innerTopic.topicPubControlValueYkParam')" prop="topicPubControlValueYkParam">
            <el-select
                v-model="innerTopicForm.topicPubControlValueYkParam"
                :placeholder="
              $t('common.placeholderSelect') + $t('innerTopic.topicPubControlValueYkParam')
            "
                clearable
            >
              <el-option
                  v-for="(item, index) in ykControlTypeEnum"
                  :key="index"
                  :label="locale ? item.cndesc : item.endesc"
                  :value="item.endesc"
              />
            </el-select>
          </el-form-item>
        </template>

        <el-form-item :label="$t('innerTopic.isEnable')" prop="isEnable">
          <el-select
              v-model="innerTopicForm.isEnable"
              :placeholder="
              $t('common.placeholderSelect') + $t('innerTopic.isEnable')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in innerTopicEnableEnums"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('innerTopic.timePeriod')" prop="timePeriod">
          <el-input-number
              :min="1" :max="9999999"
              v-model="innerTopicForm.timePeriod"
              :placeholder="
              $t('common.placeholderInput') + $t('innerTopic.timePeriod')
            "
          />
        </el-form-item>
        <!-- 可扩展：如需其他表单项（如“颜色”“描述”），直接在这里添加 -->
      </template>
    </CommonFormDialog>

    <el-card>
      <el-row>
        <el-col :span="24">
          <el-card
          ><!-- 数据表格 -->
            <el-table
                max-height="600"
                :data="tableData"
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
              <el-table-column
                  :label="$t('common.sn')"
                  type="index"
                  width="150"
              />

              <el-table-column
                  :label="$t('innerTopic.topicAssociationMode')"
                  align="center"
                  prop="topicAssociationMode"
              >
                <template #default="scope">
                  {{getTopicAssociationModeName(scope.row.topicAssociationMode)}}
                </template>
              </el-table-column>
              <el-table-column
                  :label="$t('innerTopic.topicPubName')"
                  align="center"
                  prop="topicPubName"
              />
              <el-table-column
                  :label="$t('innerTopic.topicSubName')"
                  align="center"
                  prop="topicSubName"
              />
              <el-table-column
                  :label="$t('innerTopic.topicPubDeviceParam')"
                  align="center"
                  prop="topicPubDeviceParam"
              />
              <el-table-column
                  :label="$t('innerTopic.topicPubSingalTypeParam')"
                  align="center"
                  prop="topicPubSingalTypeParam"
              />
              <el-table-column
                  :label="$t('innerTopic.topicPubSysunitTypeParam')"
                  align="center"
                  prop="topicPubSysunitTypeParam"
              />
              <el-table-column
                  :label="$t('innerTopic.orderNo')"
                  align="center"
                  prop="topicSequence"
              />
              <el-table-column
                  :label="$t('innerTopic.topicGroup')"
                  align="center"
                  prop="topicGroup"
              />
              <el-table-column
                  :label="$t('innerTopic.topicPubAddrStartParam')"
                  align="center"
                  prop="topicPubAddrStartParam"
              />
              <el-table-column
                  :label="$t('innerTopic.topicPubAddrNumParam')"
                  align="center"
                  prop="topicPubAddrNumParam"
              />
              <el-table-column
                  :label="$t('innerTopic.topicPubControlValueYtParam')"
                  align="center"
                  prop="topicPubControlValueYtParam"
              />
              <el-table-column
                  :label="$t('innerTopic.topicPubControlValueYkParam')"
                  align="center"
                  prop="topicPubControlValueYkParam"
              />
              <el-table-column
                  :label="$t('innerTopic.isEnable')"
                  align="center"
                  prop="isEnable"
              >
                <template #default="scope">
                  {{getInnerTopicEnableName(scope.row.isEnable)}}
                </template>
              </el-table-column>
              <el-table-column
                  :label="$t('innerTopic.timePeriod')"
                  align="center"
                  prop="timePeriod"
              />

              <el-table-column
                  :label="$t('common.createTime')"
                  align="center"
                  prop="createTime"
              />
              <el-table-column
                  :label="$t('common.updateTime')"
                  align="center"
                  prop="updateTime"
              />
              <el-table-column
                  label="操作"
                  align="center"
                  width="150"
                  fixed="right"
              >
                <template #default="scope">

                  <el-button
                      type="primary"
                      link
                      icon="Edit"
                      @click="updateinnerTopic(scope.row)"
                  >{{ $t("common.edit") }}
                  </el-button
                  >
                  <el-button
                      type="danger"
                      link
                      icon="Delete"
                      @click="handleDelete(scope.row)"
                  >{{ $t("common.delete") }}
                  </el-button
                  >

                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                  v-model:current-page="innerTopicQueryForm.pageNum"
                  v-model:page-size="innerTopicQueryForm.pageSize"
                  :page-sizes="[10, 20, 30, 50]"
                  :total="total"
                  :background="true"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import {
  gettopicInnerPageApi,
  gettopicInnerListApi,
  addtopicInnerApi,
  updatetopicInnerApi,
  deltopicInnerApi,
} from "@/api/ems/topic/topicInner.ts";
import {EmsinnerTopicEnum} from "@/enum/EmsinnerTopicEnum"
import {EmsCommonEnums} from "@/enum/common/EmsCommonEnums"
import {publishDevConfApi, subscribeDevConfApi} from "@/api/mqtt"
import {useRoute, useRouter} from "vue-router";
import {getEnumListByType} from "@/api/enums";
import {ElMessage, ElMessageBox, ElLoading} from "element-plus";
import {useI18n} from "vue-i18n";
import CommonFormDialog from "@/components/Modal/basicModal.vue"; // 引入通用组件
import {reactive, ref, onMounted, onUnmounted} from "vue";

const tableData = ref(); //表格数组
const locale = ref(window.localStorage.getItem("locale") == "zh-CN");
const router = useRouter();
const total = ref(0);
const dialogWidth = ref("600px");
// 1. 对话框状态
const dialogVisible = ref(false); // 对话框是否显示

const submitLoading = ref(false); // 提交按钮加载状态
const dialogRef = ref(); // 通用对话框组件引用
const {t} = useI18n();
const dialogTitle = ref(); // 对话框标题
// 2. 设备查询表单数据
const innerTopicQueryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  id: null, // 内部主题Id
  channelConfId: null, // 通道Id
  topicPubSingalTypeParam: null,//主题发布信号类型参数
});
// 2. 设备新增表单数据
const innerTopicForm = reactive({
  topicAssociationMode: "", //
  topicPubName: "",
  topicSubName: "",
  topicPubDeviceParam: 0,
  topicPubSingalTypeParam: 'yc',
  topicPubSysunitTypeParam: null,
  topicSequence: null,
  topicGroup: null,
  topicPubAddrStartParam: null,
  topicPubAddrNumParam: null,
  topicPubControlValueYtParam: null,
  topicPubControlValueYkParam: null,
  isEnable: null,
  timePeriod: null,
  channelConfId: null
});
// 3. 标签表单校验规则
const innerTopicRules = reactive({
  topicAssociationMode: [
    {
      required: true,
      message: t("common.placeholderSelect"),
      trigger: "change",
    },
  ],
  topicPubName: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
    {max: 50, message: t("common.inputRule"), trigger: "blur"},
  ],
  topicSubName: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
    {max: 50, message: t("common.inputRule"), trigger: "blur"},
  ],
  topicPubDeviceParam: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
    {max: 50, message: t("innerTopic.inputRule"), trigger: "blur"},
  ],
  topicPubSingalTypeParam: [
    {
      required: true,
      message: t("common.placeholderSelect"),
      trigger: "change",
    },
  ],
  topicPubSysunitTypeParam: [
    {
      required: true,
      message: t("common.placeholderSelect"),
      trigger: "change",
    },
  ],
  topicSequence: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
  ],
  topicPubAddrStartParam: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
  ],
  topicPubAddrNumParam: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
  ],
  topicPubControlValueYtParam: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
  ], topicPubControlValueYkParam: [
    {
      required: true,
      message: t("common.placeholderSelect"),
      trigger: "change",
    },
  ], isEnable: [
    {
      required: true,
      message: t("common.placeholderSelect"),
      trigger: "change",
    },
  ],
});
//
//设  备列表
const innerTopicList = ref([]);
//设备可用列表枚举
const innerTopicEnableEnums = ref([]);
//主题关联模式枚举
const topicAssociationModeEnums = ref([]);
//信号类型
const singalTypeParamEnums = ref([]);
//系统/单元枚举
const emsSyCategorEnums = ref([]);
const ykControlTypeEnums = ref([])
//查询设备列表
const getinnerTopicList = () => {
  gettopicInnerListApi().then((res) => {
    innerTopicList.value = res.data;
  });
};
//查询
const search = () => {
  getSelectPage();
};

const handleSizeChange = (val) => {
  innerTopicQueryForm.pageSize = val;
  getSelectPage();
};
const handleCurrentChange = (val) => {

  innerTopicQueryForm.pageNum = val;
  getSelectPage();
};
//发布消息
const publishDevConf = (id) => {
  publishDevConfApi({pKey: "Pkey" + id, sn: "Sn" + id, data: "sending"}).then((res) => {
    ElMessage.success(res.message);
  });
}
const subscribeDevConf = (id) => {
  subscribeDevConfApi({pKey: "Pkey" + id, sn: "Sn" + id}).then((res) => {
    ElMessage.success(res.message);
  });
}

const getSelectPage = () => {
  gettopicInnerPageApi(innerTopicQueryForm).then((res) => {
    total.value = res.data.total;
    tableData.value = res.data.records;
  });
};

//获取设备枚举列表
const getEnumListByTypeList = async (stype) => {
  let res = await getEnumListByType({type: stype});
  if (stype == EmsCommonEnums.CommonEnable) {
    innerTopicEnableEnums.value = res.data;
  }
  if (stype == EmsinnerTopicEnum.SingalTypeEnum) {
    singalTypeParamEnums.value = res.data;
  }
  if (stype == EmsinnerTopicEnum.EmsSyCategorEnum) {
    emsSyCategorEnums.value = res.data;
  }
  if (stype == EmsinnerTopicEnum.TopicAssociationModeEnum) {
    topicAssociationModeEnums.value = res.data;
  }
  if (stype == EmsinnerTopicEnum.YkControlTypeEnum) {
    ykControlTypeEnums.value = res.data;
  }
};
// 关闭对话框时，触发 update:modelValue 事件
const close = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
// 关闭对话框时，触发 update:modelValue 事件
const cancel = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//新增调出弹框
const addinnerTopic = () => {
  dialogVisible.value = true;
  Object.assign(innerTopicForm, {
    id: null,
    topicAssociationMode: 2, //
    topicPubName: "",
    topicSubName: "",
    topicPubDeviceParam: "",
    topicPubSingalTypeParam: 'yc',
    topicPubSysunitTypeParam: null,
    topicSequence: null,
    topicGroup: null,
    topicPubAddrStartParam: null,
    topicPubAddrNumParam: null,
    topicPubControlValueYtParam: null,
    topicPubControlValueYkParam: null,
    isEnable: null,
    timePeriod: null,
    channelConfId: channelConfId.value
  });
  dialogTitle.value = t("innerTopic.topicAdd");
};
//修改调出弹框
const innerTopicId = ref();
const updateinnerTopic = (row) => {
  dialogTitle.value = t("innerTopic.topicUpdate");
  dialogVisible.value = true;
  innerTopicId.value = row.id;
  Object.assign(innerTopicForm, row);
};
const handleDialogBeforeClose = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//提交数据
const handleFormSubmit = () => {
  if (dialogTitle.value == t("innerTopic.topicAdd")) {
    addtopicInnerApi(innerTopicForm).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.success"));
      }
    });
  } else {
    updatetopicInnerApi(Object.assign(innerTopicForm)).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.success"));
      }
    });
  }
};
//根据关联模式ID获取名称
const getTopicAssociationModeName = (id) => {
  if(locale){
    return topicAssociationModeEnums.value.find((item) => item.code == id).cndesc;
  }
  return topicAssociationModeEnums.value.find((item) => item.code == id).name;
}
//根据可用状态ID获取名称
const getInnerTopicEnableName = (id) => {
  if(locale){
    return innerTopicEnableEnums.value.find((item) => item.code == id).cndesc;
  }
  return innerTopicEnableEnums.value.find((item) => item.code == id).endesc;

}
//自动填入订阅主题
const handleTopicPubNameChange = (val) => {
  if (innerTopicForm.topicAssociationMode == 2) {

    if (val == "/cloud/${pKey}/${sn}/status/call") {
      innerTopicForm.topicSubName = "/control/${pKey}/${sn}/status";
    }
    if (val == "/cloud/${pKey}/${sn}/rtg/call") {
      innerTopicForm.topicSubName = "/control/${pKey}/${sn}/rtg";
    }
    if (val == "/cloud/${pKey}/${sn}/cmd/set") {
      innerTopicForm.topicSubName = "/control/${pKey}/${sn}/cmd/set/ack";
    }
    if (val == "/cloud/${pKey}/${sn}/file/call") {
      innerTopicForm.topicSubName = "/control/${pKey}/${sn}/file/ack";
    }
  }
}
const handleTopicPubSingalTypeParamChange = (val) => {

      innerTopicForm.topicGroup = val;

}
//删除数据
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deltopicInnerApi(row.id).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  });
};
const channelConfId = ref()
const route = useRoute();
onMounted(() => {
  console.log(typeof(Number(route.query.channelConfId)))
  channelConfId.value = Number(route.query.channelConfId)
  innerTopicQueryForm.channelConfId = channelConfId.value
  innerTopicForm.channelConfId = channelConfId.value
  getSelectPage();
  getinnerTopicList();
  getEnumListByTypeList(EmsCommonEnums.CommonEnable); //获取设备可用
  getEnumListByTypeList(EmsinnerTopicEnum.EmsSyCategorEnum); //获取设备可用
  getEnumListByTypeList(EmsinnerTopicEnum.SingalTypeEnum); //获取设备可用
  getEnumListByTypeList(EmsinnerTopicEnum.TopicAssociationModeEnum); //获取设备可用
  getEnumListByTypeList(EmsinnerTopicEnum.YkControlTypeEnum); //获取设备可用
});
onUnmounted(() => {
});
</script>
<style lang="scss" scoped>
:root[data-theme="dark"] {
  .app-container {
    :deep(.el-dialog) {
      .el-form {
        .el-input__wrapper {
          box-shadow: 0 0 0 1px var(--el-border-color) inset;
        }
      }
    }
  }
}

.app-container {
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  :deep(.el-dialog) {
    .el-dialog__body {
      padding: 20px 40px;
    }

    .el-form {
      .el-form-item {
        margin-bottom: 22px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          font-weight: 500;
          padding-right: 20px;
        }
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
